use std::env;
use std::fs;
use std::path::Path;

fn main() {
    let out_dir = env::var("OUT_DIR").unwrap();
    let rocks_out_dir = env::var("DEP_ROCKSDB_OUT_DIR").unwrap();
    let rocks_src_dir = env::var("DEP_ROCKSDB_CARGO_MANIFEST_DIR").unwrap();

    // Strip components like "build/librocks-exp-86c5a7f4d6390c5a/out" to arrive at the
    // base build profile directory (such as "target/debug"),
    let dest_dir = (out_dir.as_ref() as &Path).join("../../../librocksdb-exp");

    // Remove a prior output directory generated by this build script.
    // It may not exist.
    let _ = fs::remove_dir_all(&dest_dir);

    // Require that we're able to create a new output directory.
    fs::create_dir(&dest_dir).unwrap();
    let dest_dir = dest_dir.canonicalize().unwrap();

    let paths = fs::read_dir(rocks_out_dir).unwrap();
    for path in paths {
        let path = path.unwrap().path();
        let name = path.file_name().unwrap();

        if name
            .to_str()
            .map(|n| n.starts_with("lib"))
            .unwrap_or_default()
        {
            let dest = dest_dir.join(name);
            std::os::unix::fs::symlink(&path, &dest).unwrap();
        }
    }

    // Also symlink RocksDB's include sources into a known location.
    {
        let src = (rocks_src_dir.as_ref() as &Path).join("rocksdb/include");
        let dest = dest_dir.join("include");
        std::os::unix::fs::symlink(&src, &dest).unwrap();
    }
    // Tell cargo to re-run this build script if it is changed. Without any rerun-if-changed tags,
    // this build script will be re-run on every build.
    println!("cargo:rerun-if-changed=build.rs");
}
